package cn.itsource.basic;

import cn.hutool.core.util.StrUtil;
import cn.itsource.org.query.BaseQuey;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import javax.persistence.Transient;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;

public interface Mybasicmapper<T extends Mybasicdomain> extends Mapper<T> {

    Class<T> getClasss();

    /**
     * 逻辑批量删除
     * @param ids
     */
    default void deleteBatch(List<Long> ids) {

        Example example = new Example(getClasss());

        example.createCriteria().andIn("id", ids);

        T t = null;
        try {
            t = getClasss().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        t.setDel(Boolean.FALSE);
        this.updateByExampleSelective(t, example);
    }

    /**
     * 逻辑删除
     * @param id
     */
    default void delete(Long id){
        Example example = new Example(getClasss());

        example.createCriteria().andEqualTo("id", id);

        T t = null;
        try {
            t = getClasss().newInstance();


        } catch (Exception e) {
            e.printStackTrace();
        }
        t.setDel(Boolean.FALSE);

        this.updateByExampleSelective(t, example);
    }
    /**
     * 分页查询抽取
     */
    default PageInfo pagelist(BaseQuey baseQuey){
        //1.分页
       PageHelper.startPage(baseQuey.getPage(),baseQuey.getRows());
        //2.高级查询
        List<T> ts = this.selectAll();
        return new PageInfo(ts);
    }

    default PageInfo findPageList1(BaseQuey baseQuey){
        //1.分页
        PageHelper.startPage(baseQuey.getPage(),baseQuey.getRows());
        //2.高级条件查询
        Example example = new Example(getClasss());
        Example.Criteria criteria = example.createCriteria();
        //获取到当前对象所有的属性
        Field[] fields = getClasss().getDeclaredFields();
        for (Field field : fields) {
            //这个方法是用来保利获取被private 修饰的字段或者方法
            field.setAccessible(true);
            Transient annotation = field.getAnnotation(Transient.class);
            if(Objects.nonNull(annotation)) continue;

            String name = field.getName();
            String type = field.getType().toString();
            if (type.contains("String")){
                if (StrUtil.isNotBlank(baseQuey.getKeyword()))
                    criteria.orLike(name,"%"+baseQuey.getKeyword()+"%");
            }
        }
        List<T> ts = this.selectByExample(example);
        return new PageInfo(ts);
    }
}

